/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.client.consumer.rebalance;

import java.util.ArrayList;
import java.util.List;
import org.apache.rocketmq.client.consumer.AllocateMessageQueueStrategy;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.common.message.MessageQueue;

/**
 * Average Hashing queue algorithm
 */
public class AllocateMessageQueueAveragely implements AllocateMessageQueueStrategy {
    private final InternalLogger log = ClientLogger.getLog();

    /**
     * 平均分配策略
     * @param consumerGroup current consumer group
     * @param currentCID current consumer id
     * @param mqAll message queue set in current topic
     * @param cidAll consumer set in current consumer group
     * @return
     */
    @Override
    public List<MessageQueue> allocate(String consumerGroup, String currentCID, List<MessageQueue> mqAll,
        List<String> cidAll) {
        if (currentCID == null || currentCID.length() < 1) {
            throw new IllegalArgumentException("currentCID is empty");
        }
        if (mqAll == null || mqAll.isEmpty()) {
            throw new IllegalArgumentException("mqAll is null or mqAll empty");
        }
        if (cidAll == null || cidAll.isEmpty()) {
            throw new IllegalArgumentException("cidAll is null or cidAll empty");
        }

        List<MessageQueue> result = new ArrayList<MessageQueue>();
        // 如果这个消费者列表中不含包当前这个id, 就返回空，因为这个broker可能还不知道这个客户端的存在，就不用他干活了
        if (!cidAll.contains(currentCID)) {
            log.info("[BUG] ConsumerGroup: {} The consumerId: {} not in cidAll: {}",
                consumerGroup,
                currentCID,
                cidAll);
            return result;
        }
        // 获取当前客户端（消费者）id在所有消费者中的位置
        int index = cidAll.indexOf(currentCID);
        // 使用所有队列 % 所欲消费者，就是看看均分的话 还剩几个是没法均分的
        int mod = mqAll.size() % cidAll.size();
        // 计算几个, 如果队列数小于消费者数，则将分到队列数设置为1，如果余数大于当前消费者的index
        // 则能分到的队列数+1，否则就是平均值
        // 比如8个mq, 3个消费者 0, 1, 2 现在我是0的位置，计算出来0分3个，1分3个，2分2个
        // 计算0位置客户端 0*3=0，1位置的 1*3=3, 2位置的 2*2+2=6
        // 0从0位置处开始取，1从3位置开始取，2从6开始取
        int averageSize =
            mqAll.size() <= cidAll.size() ? 1 : (mod > 0 && index < mod ? mqAll.size() / cidAll.size()
                + 1 : mqAll.size() / cidAll.size());
        // consumer 获取第一个messageQueue的索引
        int startIndex = (mod > 0 && index < mod) ? index * averageSize : index * averageSize + mod;
        // 如果消费者数大于队列数，range会是负数，循环则不会执行
        // 0的range = averageSize = 3, 1的range = 3， 2的range = 2
        int range = Math.min(averageSize, mqAll.size() - startIndex);
        // 顺序的
        for (int i = 0; i < range; i++) {
            // 0 第一次(0+0) % 8 = 0, 第二次 (0+1)%8 = 1
            result.add(mqAll.get((startIndex + i) % mqAll.size()));
        }
        // 返回的是当期前消费者分配的messageQueue集合
        return result;
    }

    @Override
    public String getName() {
        return "AVG";
    }
}
